package strategic_monitor

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/common/bid_content"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/common/constants"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/common/ossfile"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/common/utils"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/repository/remote/openapi_remote"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/repository/strategic_monitor"
	pb "git.mycaigou.com/gfyx/micro-gfyx-user-service/proto/micro_gfyx_user_service_proto/micro-gfyx-user-service"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/service/file"
	"github.com/xuri/excelize/v2"
	"net/http"
	"strconv"
	"strings"
	"time"
)

type strategicMonitorService struct {
	strategicMonitorRepo strategic_monitor.StrategicMonitorRepositoryIface
	openapiRepo          openapi_remote.OpenApiRepoIface
	fileService          file.FileServiceIface
}

func NewStrategicMonitorService(
	strategicMonitorRepo strategic_monitor.StrategicMonitorRepositoryIface,
	openapiRepo openapi_remote.OpenApiRepoIface,
	fileService file.FileServiceIface,
) StrategicMonitorServiceIface {
	return &strategicMonitorService{
		strategicMonitorRepo: strategicMonitorRepo,
		openapiRepo:          openapiRepo,
		fileService:          fileService,
	}
}

func buildBidListCondition(request *pb.GetStrategicBidListRequest) map[string]interface{} {
	if request == nil {
		return nil
	}
	condition := map[string]interface{}{"is_deleted": constants.IsDeletedFalse}
	if request.Keyword != "" {
		condition["keyword"] = request.Keyword
	}
	if len(request.AuditStatus) > 0 {
		condition["audit_status"] = request.AuditStatus
	}
	return condition
}

func (s *strategicMonitorService) GetStrategicBidList(ctx context.Context, request *pb.GetStrategicBidListRequest) (*pb.GetStrategicBidListResponse, error) {
	condition := buildBidListCondition(request)
	pageInfo := &utils.PageInfo{
		PageSize: 20,
		Page:     1,
		Total:    0,
	}
	if request.Page > 0 && request.PageSize > 0 {
		pageInfo.Page = int(request.Page)
		pageInfo.PageSize = int(request.PageSize)
	}

	switch request.BidType {
	case 1:
		return s.getStrategicBidList(ctx, condition, pageInfo)
	case 2:
		return s.getStrategicWinbidList(ctx, condition, pageInfo)
	default:
		return nil, errors.New("公告类型错误")
	}
}

func (s *strategicMonitorService) getStrategicBidList(ctx context.Context, condition map[string]interface{}, pageInfo *utils.PageInfo) (*pb.GetStrategicBidListResponse, error) {
	total, bidList, err := s.strategicMonitorRepo.QueryStrategicBidList(ctx, condition, pageInfo)
	if err != nil {
		return nil, err
	}
	resp := &pb.GetStrategicBidListResponse{
		Total: int32(total),
	}

	for _, item := range bidList {
		resp.List = append(resp.List, &pb.StrategicBidItem{
			Id:          item.Id,
			BidType:     1,
			CompanyName: item.CompanyName,
			PublishTime: item.PublishDate.Format("2006-01-02 15:04:05"),
			Title:       item.Title,
			AuditStatus: item.AuditStatus,
		})
	}
	return resp, nil
}

func (s *strategicMonitorService) getStrategicWinbidList(ctx context.Context, condition map[string]interface{}, pageInfo *utils.PageInfo) (*pb.GetStrategicBidListResponse, error) {
	total, winbidList, err := s.strategicMonitorRepo.QueryStrategicWinbidList(ctx, condition, pageInfo)
	if err != nil {
		return nil, err
	}
	resp := &pb.GetStrategicBidListResponse{
		Total: int32(total),
	}

	for _, item := range winbidList {
		resp.List = append(resp.List, &pb.StrategicBidItem{
			Id:          item.Id,
			BidType:     2,
			CompanyName: item.CompanyName,
			PublishTime: item.PublishDate.Format("2006-01-02 15:04:05"),
			Title:       item.Title,
			AuditStatus: item.AuditStatus,
		})
	}
	return resp, nil
}

func (s *strategicMonitorService) getStrategicBidDetail(ctx context.Context, request *pb.GetStrategicBidDetailRequest) (*pb.GetStrategicBidDetailResponse, error) {
	condition := map[string]interface{}{"id": request.Id, "is_deleted": constants.IsDeletedFalse}
	_, list, err := s.strategicMonitorRepo.QueryStrategicBidList(ctx, condition, utils.FirstPageFirstRecord)
	if err != nil {
		return nil, err
	}
	if len(list) == 0 {
		return nil, errors.New("数据不存在")
	}

	bidPo := list[0]
	resp := &pb.GetStrategicBidDetailResponse{
		Id:          bidPo.Id,
		BidType:     1,
		CompanyName: bidPo.CompanyName,
		PublishTime: bidPo.PublishDate.Format("2006-01-02 15:04:05"),
		ProcureType: 0,
		StartYear:   bidPo.StartYear,
		EndYear:     bidPo.EndYear,
		Content:     "",
		SourceUrl:   bidPo.SourceUrl,
		Industries:  nil,
	}
	resp.Content, _ = bid_content.GetBidContent("bid", bidPo.PublishDate.Format("2006-01-02"), bidPo.SourceWebsite, bidPo.ContentId)

	if bidPo.AuditStatus == constants.AuditStatusAudited {
		// 如果是审核通过的数据，需要从审核表中获取产品品类和集采类型
		_, auditList, _ := s.strategicMonitorRepo.QueryStrategicBidAuditList(ctx,
			map[string]interface{}{"bid_id": bidPo.BidId, "is_deleted": constants.IsDeletedFalse},
			utils.FirstPageFirstRecord)
		if len(auditList) > 0 {
			resp.ProcureType = auditList[0].ProcureType

			industries, _ := s.strategicMonitorRepo.QueryStrategicIndustryByAuditId(ctx, auditList[0].Id)
			for _, item := range industries {
				resp.Industries = append(resp.Industries, &pb.IndustryItem{
					Id:           item.Id,
					IndustryName: item.IndustryName,
				})
			}
		}
	}
	return resp, nil
}

func (s *strategicMonitorService) getStrategicWinbidDetail(ctx context.Context, request *pb.GetStrategicBidDetailRequest) (*pb.GetStrategicBidDetailResponse, error) {
	condition := map[string]interface{}{"id": request.Id, "is_deleted": constants.IsDeletedFalse}
	_, list, err := s.strategicMonitorRepo.QueryStrategicWinbidList(ctx, condition, utils.FirstPageFirstRecord)
	if err != nil {
		return nil, err
	}
	if len(list) == 0 {
		return nil, errors.New("数据不存在")
	}

	bidPo := list[0]
	resp := &pb.GetStrategicBidDetailResponse{
		Id:          bidPo.Id,
		BidType:     2,
		CompanyName: bidPo.CompanyName,
		PublishTime: bidPo.PublishDate.Format("2006-01-02 15:04:05"),
		ProcureType: 0,
		StartYear:   bidPo.StartYear,
		EndYear:     bidPo.EndYear,
		Content:     "",
		SourceUrl:   bidPo.SourceUrl,
		Industries:  nil,
	}
	resp.Content, _ = bid_content.GetBidContent("winbid", bidPo.PublishDate.Format("2006-01-02"), bidPo.SourceWebsite, bidPo.ContentId)

	if bidPo.AuditStatus == constants.AuditStatusAudited {
		// 如果是审核通过的数据，需要从审核表中获取产品品类和集采类型
		_, auditList, _ := s.strategicMonitorRepo.QueryStrategicBidAuditList(ctx,
			map[string]interface{}{"bid_id": bidPo.WinbidId, "is_deleted": constants.IsDeletedFalse},
			utils.FirstPageFirstRecord)
		if len(auditList) > 0 {
			resp.ProcureType = auditList[0].ProcureType

			industries, _ := s.strategicMonitorRepo.QueryStrategicIndustryByAuditId(ctx, auditList[0].Id)
			for _, item := range industries {
				resp.Industries = append(resp.Industries, &pb.IndustryItem{
					Id:           item.Id,
					IndustryName: item.IndustryName,
				})
			}
		}
	}
	return resp, nil
}

func (s *strategicMonitorService) GetStrategicBidDetail(ctx context.Context, request *pb.GetStrategicBidDetailRequest) (*pb.GetStrategicBidDetailResponse, error) {
	if request == nil || request.Id == 0 || (request.BidType != 1 && request.BidType != 2) {
		return nil, errors.New("参数错误")
	}
	switch request.BidType {
	case 1:
		return s.getStrategicBidDetail(ctx, request)
	case 2:
		return s.getStrategicWinbidDetail(ctx, request)

	default:
		return nil, errors.New("公告类型错误")
	}
}

func (s *strategicMonitorService) auditStrategicBid(ctx context.Context, request *pb.AuditStrategicBidRequest) (*pb.AuditStrategicBidResponse, error) {
	// 入参检查
	if request == nil || request.CompanyName == "" {
		return nil, errors.New("参数错误")
	}
	publishDate, err := time.ParseInLocation("2006-01-02 15:04:05", request.PublishTime, time.Local)
	if err != nil {
		return nil, errors.New("发布时间参数格式错误")
	}
	// 检查公司的工商信息
	companyDetail, err := s.openapiRepo.GetCompanyDetail(ctx, request.CompanyName)
	if err != nil {
		return nil, err
	}
	if companyDetail == nil || companyDetail.OrganizingCode == "" {
		return nil, errors.New("企业工商信息不存在，请核对后重新输入")
	}

	condition := map[string]interface{}{"id": request.Id, "is_deleted": constants.IsDeletedFalse}
	_, list, err := s.strategicMonitorRepo.QueryStrategicBidList(ctx, condition, utils.FirstPageFirstRecord)
	if err != nil {
		return nil, err
	}
	if len(list) == 0 {
		return nil, errors.New("数据不存在")
	}

	bidPo := list[0]

	hasAuditRecord := false
	var auditPo *strategic_monitor.StrategicBidAudit
	if bidPo.AuditStatus == constants.AuditStatusAudited {
		// 已审核的数据
		// 修改strategic_bid_audit、strategic_bid_company、strategic_bid_industry表中的对应数据
		_, auditList, err := s.strategicMonitorRepo.QueryStrategicBidAuditList(ctx,
			map[string]interface{}{"bid_id": bidPo.BidId, "is_deleted": constants.IsDeletedFalse}, utils.FirstPageFirstRecord)
		if err != nil {
			return nil, err
		}
		if len(auditList) != 0 {
			hasAuditRecord = true
			auditPo = auditList[0]
		}
	}

	// 1.更新strategic_bid表的audit_status为已审核
	err = s.strategicMonitorRepo.UpdateStrategicBid(ctx, condition,
		map[string]interface{}{
			"audit_status":    constants.AuditStatusAudited,
			"company_name":    request.CompanyName,
			"organizing_code": companyDetail.OrganizingCode,
			"publish_date":    request.PublishTime,
			"start_year":      request.StartYear,
			"end_year":        request.EndYear,
		})
	if err != nil {
		return nil, err
	}
	// 2.将审核通过的数据保存到strategic_bid_audit、strategic_bid_company、strategic_bid_industry表中
	// todo strategic_bid_audit表做唯一性校验
	// title、company_name、organizing_code、publish_date、procure_type、start_year、end_year，8个值全相同，则判断为唯一
	if !hasAuditRecord {
		auditPo, err = s.strategicMonitorRepo.SaveStrategicBidAudit(ctx, &strategic_monitor.StrategicBidAudit{
			Id:             0,
			BidId:          bidPo.BidId,
			Title:          bidPo.Title,
			CompanyName:    request.CompanyName,
			OrganizingCode: companyDetail.OrganizingCode,
			PublishDate:    publishDate,
			ProcureType:    request.ProcureType,
			StartYear:      request.StartYear,
			EndYear:        request.EndYear,
			CreatedBy:      request.AuditUser,
			CreatedOn:      time.Now(),
			ModifiedBy:     request.AuditUser,
			ModifiedOn:     time.Now(),
			IsDeleted:      constants.IsDeletedFalse,
		})
		if err != nil {
			return nil, err
		}
	} else {
		auditPo.CompanyName = request.CompanyName
		auditPo.OrganizingCode = companyDetail.OrganizingCode
		auditPo.PublishDate = publishDate
		auditPo.ProcureType = request.ProcureType
		auditPo.StartYear = request.StartYear
		auditPo.EndYear = request.EndYear
		auditPo.ModifiedOn = time.Now()
		auditPo.ModifiedBy = request.AuditUser
		err = s.strategicMonitorRepo.UpdateStrategicBidAudit(ctx, map[string]interface{}{"id": auditPo.Id},
			map[string]interface{}{
				"company_name": auditPo.CompanyName, "organizing_code": auditPo.OrganizingCode,
				"publish_date": auditPo.PublishDate, "procure_type": auditPo.ProcureType,
				"start_year": auditPo.StartYear, "end_year": auditPo.EndYear,
				"modified_on": time.Now(), "modified_by": auditPo.ModifiedBy})
		if err != nil {
			return nil, err
		}
	}

	_, companyList, err := s.strategicMonitorRepo.QueryStrategicBidCompanyList(ctx,
		map[string]interface{}{"organizing_code": auditPo.OrganizingCode, "is_deleted": constants.IsDeletedFalse},
		utils.FirstPageFirstRecord)
	if err != nil {
		return nil, err
	}
	if len(companyList) == 0 {
		_, err = s.strategicMonitorRepo.SaveStrategicBidCompany(ctx, &strategic_monitor.StrategicBidCompany{
			Id:             0,
			CompanyName:    auditPo.CompanyName,
			OrganizingCode: auditPo.OrganizingCode,
			Province:       companyDetail.Province,
			ProvinceCode:   companyDetail.ProvinceCode,
			City:           companyDetail.City,
			CityCode:       companyDetail.CityCode,
			AuditStatus:    constants.AuditStatusAudited,
			AuditTime: sql.NullTime{
				Time:  time.Now(),
				Valid: true,
			},
			AuditBy:    request.AuditUser,
			CreatedBy:  request.AuditUser,
			CreatedOn:  time.Now(),
			ModifiedBy: request.AuditUser,
			ModifiedOn: time.Now(),
			IsDeleted:  constants.IsDeletedFalse,
		})
		if err != nil {
			return nil, err
		}
	} else {
		// 企业已存在，如果审核状态是待审核或审核不通过，那么修改审核状态为审核通过
		if companyList[0].AuditStatus != constants.AuditStatusAudited {
			_ = s.strategicMonitorRepo.UpdateStrategicBidCompany(ctx, map[string]interface{}{"id": companyList[0].Id},
				map[string]interface{}{"audit_status": constants.AuditStatusAudited, "audit_by": request.AuditUser, "audit_time": time.Now()})
		}
	}

	if len(request.IndustryNameArr) != 0 {
		// 删除旧的分类，新增新的分类
		err = s.strategicMonitorRepo.UpdateStrategicBidIndustry(ctx, map[string]interface{}{"audit_id": auditPo.Id, "is_deleted": constants.IsDeletedFalse},
			map[string]interface{}{"is_deleted": constants.IsDeletedTrue, "modified_by": request.AuditUser, "modified_on": time.Now()})
		for _, industryName := range request.IndustryNameArr {
			_, industryList, err := s.strategicMonitorRepo.QueryStrategicIndustryList(ctx,
				map[string]interface{}{"industry_name": industryName, "is_deleted": constants.IsDeletedFalse},
				utils.FirstPageFirstRecord)
			if err != nil {
				return nil, err
			}
			var industryId int64
			if len(industryList) == 0 {
				// 产品品类不存在，直接新增品类
				industryPo, err := s.strategicMonitorRepo.SaveStrategicIndustry(ctx, &strategic_monitor.StrategicIndustry{
					Id:           0,
					IndustryName: industryName,
					AuditStatus:  constants.AuditStatusAudited,
					AuditTime: sql.NullTime{
						Time:  time.Now(),
						Valid: true,
					},
					AuditBy:    request.AuditUser,
					CreatedBy:  request.AuditUser,
					CreatedOn:  time.Now(),
					ModifiedBy: request.AuditUser,
					ModifiedOn: time.Now(),
					IsDeleted:  constants.IsDeletedFalse,
				})
				if err != nil {
					return nil, err
				}
				industryId = industryPo.Id
			} else {
				industryId = industryList[0].Id
			}

			_, err = s.strategicMonitorRepo.SaveStrategicBidIndustry(ctx, &strategic_monitor.StrategicBidIndustry{
				Id:         0,
				AuditId:    auditPo.Id,
				IndustryId: industryId,
				CreatedBy:  request.AuditUser,
				CreatedOn:  time.Now(),
				ModifiedBy: request.AuditUser,
				ModifiedOn: time.Now(),
				IsDeleted:  constants.IsDeletedFalse,
			})
			if err != nil {
				return nil, err
			}
		}
	}

	return &pb.AuditStrategicBidResponse{IsSuccess: true}, nil
}

func (s *strategicMonitorService) auditStrategicWinbid(ctx context.Context, request *pb.AuditStrategicBidRequest) (*pb.AuditStrategicBidResponse, error) {
	// 入参检查
	if request == nil || request.CompanyName == "" {
		return nil, errors.New("参数错误")
	}
	publishDate, err := time.ParseInLocation("2006-01-02 15:04:05", request.PublishTime, time.Local)
	if err != nil {
		return nil, errors.New("发布时间参数格式错误")
	}
	// 检查公司的工商信息
	companyDetail, err := s.openapiRepo.GetCompanyDetail(ctx, request.CompanyName)
	if err != nil {
		return nil, err
	}
	if companyDetail == nil || companyDetail.OrganizingCode == "" {
		return nil, errors.New("企业工商信息不存在，请核对后重新输入")
	}

	condition := map[string]interface{}{"id": request.Id, "is_deleted": constants.IsDeletedFalse}
	_, list, err := s.strategicMonitorRepo.QueryStrategicWinbidList(ctx, condition, utils.FirstPageFirstRecord)
	if err != nil {
		return nil, err
	}
	if len(list) == 0 {
		return nil, errors.New("数据不存在")
	}

	winbidPo := list[0]

	hasAuditRecord := false
	var auditPo *strategic_monitor.StrategicBidAudit
	if winbidPo.AuditStatus == constants.AuditStatusAudited {
		// 已审核的数据
		// 修改strategic_bid_audit、strategic_bid_company、strategic_bid_industry表中的对应数据
		_, auditList, err := s.strategicMonitorRepo.QueryStrategicBidAuditList(ctx,
			map[string]interface{}{"bid_id": winbidPo.WinbidId, "is_deleted": constants.IsDeletedFalse}, utils.FirstPageFirstRecord)
		if err != nil {
			return nil, err
		}
		if len(auditList) != 0 {
			hasAuditRecord = true
			auditPo = auditList[0]
		}
	}

	// 1.更新strategic_bid表的audit_status为已审核
	err = s.strategicMonitorRepo.UpdateStrategicWinbid(ctx, condition,
		map[string]interface{}{
			"audit_status":    constants.AuditStatusAudited,
			"company_name":    request.CompanyName,
			"organizing_code": companyDetail.OrganizingCode,
			"publish_date":    request.PublishTime,
			"start_year":      request.StartYear,
			"end_year":        request.EndYear,
		})
	if err != nil {
		return nil, err
	}
	// 2.将审核通过的数据保存到strategic_bid_audit、strategic_bid_company、strategic_bid_industry表中
	if !hasAuditRecord {
		auditPo, err = s.strategicMonitorRepo.SaveStrategicBidAudit(ctx, &strategic_monitor.StrategicBidAudit{
			Id:             0,
			BidId:          winbidPo.WinbidId,
			Title:          winbidPo.Title,
			CompanyName:    request.CompanyName,
			OrganizingCode: companyDetail.OrganizingCode,
			PublishDate:    publishDate,
			ProcureType:    request.ProcureType,
			StartYear:      request.StartYear,
			EndYear:        request.EndYear,
			CreatedBy:      request.AuditUser,
			CreatedOn:      time.Now(),
			ModifiedBy:     request.AuditUser,
			ModifiedOn:     time.Now(),
			IsDeleted:      constants.IsDeletedFalse,
		})
		if err != nil {
			return nil, err
		}
	} else {
		auditPo.CompanyName = request.CompanyName
		auditPo.OrganizingCode = companyDetail.OrganizingCode
		auditPo.PublishDate = publishDate
		auditPo.ProcureType = request.ProcureType
		auditPo.StartYear = request.StartYear
		auditPo.EndYear = request.EndYear
		auditPo.ModifiedOn = time.Now()
		auditPo.ModifiedBy = request.AuditUser
		err = s.strategicMonitorRepo.UpdateStrategicBidAudit(ctx, map[string]interface{}{"id": auditPo.Id},
			map[string]interface{}{
				"company_name": auditPo.CompanyName, "organizing_code": auditPo.OrganizingCode,
				"publish_date": auditPo.PublishDate, "procure_type": auditPo.ProcureType,
				"start_year": auditPo.StartYear, "end_year": auditPo.EndYear,
				"modified_on": time.Now(), "modified_by": auditPo.ModifiedBy})
		if err != nil {
			return nil, err
		}
	}

	_, companyList, err := s.strategicMonitorRepo.QueryStrategicBidCompanyList(ctx,
		map[string]interface{}{"organizing_code": auditPo.OrganizingCode, "is_deleted": constants.IsDeletedFalse},
		utils.FirstPageFirstRecord)
	if err != nil {
		return nil, err
	}
	if len(companyList) == 0 {
		_, err = s.strategicMonitorRepo.SaveStrategicBidCompany(ctx, &strategic_monitor.StrategicBidCompany{
			Id:             0,
			CompanyName:    auditPo.CompanyName,
			OrganizingCode: auditPo.OrganizingCode,
			Province:       companyDetail.Province,
			ProvinceCode:   companyDetail.ProvinceCode,
			City:           companyDetail.City,
			CityCode:       companyDetail.CityCode,
			AuditStatus:    constants.AuditStatusAudited,
			AuditTime: sql.NullTime{
				Time:  time.Now(),
				Valid: true,
			},
			AuditBy:    request.AuditUser,
			CreatedBy:  request.AuditUser,
			CreatedOn:  time.Now(),
			ModifiedBy: request.AuditUser,
			ModifiedOn: time.Now(),
			IsDeleted:  constants.IsDeletedFalse,
		})
		if err != nil {
			return nil, err
		}
	} else {
		// 企业已存在，如果审核状态是待审核或审核不通过，那么修改审核状态为审核通过
		if companyList[0].AuditStatus != constants.AuditStatusAudited {
			_ = s.strategicMonitorRepo.UpdateStrategicBidCompany(ctx, map[string]interface{}{"id": companyList[0].Id},
				map[string]interface{}{"audit_status": constants.AuditStatusAudited, "audit_by": request.AuditUser, "audit_time": time.Now()})
		}
	}

	if len(request.IndustryNameArr) != 0 {
		// 删除旧的分类，新增新的分类
		err = s.strategicMonitorRepo.UpdateStrategicBidIndustry(ctx, map[string]interface{}{"audit_id": auditPo.Id, "is_deleted": constants.IsDeletedFalse},
			map[string]interface{}{"is_deleted": constants.IsDeletedTrue, "modified_by": request.AuditUser, "modified_on": time.Now()})
		for _, industryName := range request.IndustryNameArr {
			_, industryList, err := s.strategicMonitorRepo.QueryStrategicIndustryList(ctx,
				map[string]interface{}{"industry_name": industryName, "is_deleted": constants.IsDeletedFalse},
				utils.FirstPageFirstRecord)
			if err != nil {
				return nil, err
			}
			var industryId int64
			if len(industryList) == 0 {
				// 产品品类不存在，直接新增品类
				industryPo, err := s.strategicMonitorRepo.SaveStrategicIndustry(ctx, &strategic_monitor.StrategicIndustry{
					Id:           0,
					IndustryName: industryName,
					AuditStatus:  constants.AuditStatusAudited,
					AuditTime: sql.NullTime{
						Time:  time.Now(),
						Valid: true,
					},
					AuditBy:    request.AuditUser,
					CreatedBy:  request.AuditUser,
					CreatedOn:  time.Now(),
					ModifiedBy: request.AuditUser,
					ModifiedOn: time.Now(),
					IsDeleted:  constants.IsDeletedFalse,
				})
				if err != nil {
					return nil, err
				}
				industryId = industryPo.Id
			} else {
				industryId = industryList[0].Id
			}

			_, err = s.strategicMonitorRepo.SaveStrategicBidIndustry(ctx, &strategic_monitor.StrategicBidIndustry{
				Id:         0,
				AuditId:    auditPo.Id,
				IndustryId: industryId,
				CreatedBy:  request.AuditUser,
				CreatedOn:  time.Now(),
				ModifiedBy: request.AuditUser,
				ModifiedOn: time.Now(),
				IsDeleted:  constants.IsDeletedFalse,
			})
			if err != nil {
				return nil, err
			}
		}
	}

	// 中标单位不为空，则添加到合作单位表中
	if winbidPo.FirstWinbidCompany != "" {
		err = s.saveNewCooperateCompany(ctx, auditPo.Id, winbidPo.FirstWinbidCompany, request.AuditUser)
		if err != nil {
			return nil, err
		}
	}
	if winbidPo.SecondWinbidCompany != "" {
		err = s.saveNewCooperateCompany(ctx, auditPo.Id, winbidPo.SecondWinbidCompany, request.AuditUser)
		if err != nil {
			return nil, err
		}
	}
	if winbidPo.ThirdWinbidCompany != "" {
		err = s.saveNewCooperateCompany(ctx, auditPo.Id, winbidPo.ThirdWinbidCompany, request.AuditUser)
		if err != nil {
			return nil, err
		}
	}

	return &pb.AuditStrategicBidResponse{IsSuccess: true}, nil
}

func (s *strategicMonitorService) saveNewCooperateCompany(ctx context.Context, auditId int64, companyName, operator string) error {
	count, _, err := s.strategicMonitorRepo.QueryStrategicBidCooperateCompanyList(ctx,
		map[string]interface{}{
			"audit_id":               auditId,
			"cooperate_company_name": companyName,
			"is_deleted":             constants.IsDeletedFalse,
		}, utils.FirstPageFirstRecord)
	if err != nil {
		return err
	}
	if count > 0 {
		return nil
	}
	_, err = s.strategicMonitorRepo.SaveStrategicBidCooperateCompany(ctx, &strategic_monitor.StrategicBidCooperateCompany{
		AuditId:              auditId,
		CooperateCompanyName: companyName,
		CreatedBy:            operator,
		CreatedOn:            time.Now(),
		ModifiedBy:           operator,
		ModifiedOn:           time.Now(),
		IsDeleted:            constants.IsDeletedFalse,
	})
	if err != nil {
		return err
	}

	return nil
}

func (s *strategicMonitorService) AuditStrategicBid(ctx context.Context, request *pb.AuditStrategicBidRequest) (*pb.AuditStrategicBidResponse, error) {
	if request == nil || request.CompanyName == "" {
		return nil, errors.New("参数错误")
	}

	switch request.BidType {
	case 1:
		return s.auditStrategicBid(ctx, request)
	case 2:
		return s.auditStrategicWinbid(ctx, request)
	default:
		return nil, errors.New("BidType参数错误")
	}
}

func buildCompanyListCondition(request *pb.GetBidCompanyListRequest) map[string]interface{} {
	condition := map[string]interface{}{"is_deleted": constants.IsDeletedFalse}

	if request == nil {
		return condition
	}

	if request.Keyword != "" {
		condition["keyword"] = request.Keyword
	}
	if len(request.AuditStatus) > 0 {
		condition["audit_status"] = request.AuditStatus
	}

	return condition
}

func (s *strategicMonitorService) GetBidCompanyList(ctx context.Context, request *pb.GetBidCompanyListRequest) (*pb.GetBidCompanyListResponse, error) {
	if request == nil {
		return nil, errors.New("参数错误")
	}
	condition := buildCompanyListCondition(request)
	pageInfo := &utils.PageInfo{PageSize: 20, Page: 1}
	if request.Page > 0 && request.PageSize > 0 {
		pageInfo = &utils.PageInfo{Page: int(request.Page), PageSize: int(request.PageSize)}
	}

	count, bidCompanyList, err := s.strategicMonitorRepo.QueryStrategicBidCompanyList(ctx, condition, pageInfo)
	if err != nil {
		return nil, err
	}
	resp := &pb.GetBidCompanyListResponse{
		Total: int32(count),
		List:  nil,
	}
	for _, bidCompany := range bidCompanyList {

		pbBidCompanyItem := &pb.BidCompanyItem{
			Id:             bidCompany.Id,
			CompanyName:    bidCompany.CompanyName,
			OrganizingCode: bidCompany.OrganizingCode,
			Province:       bidCompany.Province,
			ProvinceCode:   bidCompany.ProvinceCode,
			City:           bidCompany.City,
			CityCode:       bidCompany.CityCode,
			AuditStatus:    bidCompany.AuditStatus,
			//AuditTime:      bidCompany.AuditTime.Time,
			AuditBy:        bidCompany.AuditBy,
			BidCount:       0,
			CooperateCount: 0,
			CreatedBy:      bidCompany.CreatedBy,
			CreatedOn:      bidCompany.CreatedOn.Format("2006-01-02 15:04:05"),
		}

		if bidCompany.AuditTime.Valid {
			pbBidCompanyItem.AuditTime = bidCompany.AuditTime.Time.Format("2006-01-02 15:04:05")
		}
		//获取公司的中标数量和合作单位数量
		condition = map[string]interface{}{
			"is_deleted": constants.IsDeletedFalse,
		}
		if bidCompany.OrganizingCode != "" {
			condition["organizing_code"] = bidCompany.OrganizingCode
		} else {
			condition["company_name"] = bidCompany.CompanyName
		}
		bidCount, _, _ := s.strategicMonitorRepo.QueryStrategicBidAuditList(ctx, condition, utils.FirstPageFirstRecord)
		if bidCount != 0 {
			pbBidCompanyItem.BidCount = int32(bidCount)
		}

		cooperateCount, _ := s.strategicMonitorRepo.CountBidCompanyCooperate(ctx, bidCompany.CompanyName, bidCompany.OrganizingCode)
		if cooperateCount != 0 {
			pbBidCompanyItem.CooperateCount = int32(cooperateCount)
		}

		resp.List = append(resp.List, pbBidCompanyItem)
	}

	return resp, nil
}

func (s *strategicMonitorService) AuditBidCompany(ctx context.Context, request *pb.AuditBidCompanyRequest) (*pb.AuditBidCompanyResponse, error) {
	if request == nil || request.Id == 0 || (request.AuditStatus != constants.AuditStatusAudited && request.AuditStatus != constants.AuditStatusReject) {
		return nil, errors.New("AuditBidCompany参数错误")
	}

	resp := &pb.AuditBidCompanyResponse{
		IsSuccess: false,
	}

	err := s.strategicMonitorRepo.UpdateStrategicBidCompany(ctx,
		map[string]interface{}{"id": request.Id},
		map[string]interface{}{"audit_status": request.AuditStatus, "audit_by": request.AuditUser, "audit_time": time.Now()})
	if err != nil {
		return nil, err
	}

	resp.IsSuccess = true
	return resp, nil
}

func (s *strategicMonitorService) AddBidCompany(ctx context.Context, request *pb.AddBidCompanyRequest) (*pb.AddBidCompanyResponse, error) {
	if request == nil || request.CompanyName == "" {
		return nil, errors.New("AddBidCompany参数错误")
	}
	companyDetail, err := s.openapiRepo.GetCompanyDetail(ctx, request.CompanyName)
	if err != nil {
		return nil, err
	}
	if companyDetail == nil || companyDetail.OrganizingCode == "" {
		return nil, errors.New("企业工商信息不存在，请核对后重新输入")
	}

	count, _, err := s.strategicMonitorRepo.QueryStrategicBidCompanyList(ctx,
		map[string]interface{}{"organizing_code": companyDetail.OrganizingCode, "is_deleted": constants.IsDeletedFalse},
		utils.FirstPageFirstRecord)
	if err != nil {
		return nil, err
	}

	if count > 0 {
		return nil, errors.New("该企业已经存在")
	}

	bidCompanyPo := &strategic_monitor.StrategicBidCompany{
		Id:             0,
		CompanyName:    companyDetail.CompanyName,
		OrganizingCode: companyDetail.OrganizingCode,
		Province:       companyDetail.Province,
		ProvinceCode:   companyDetail.ProvinceCode,
		City:           companyDetail.City,
		CityCode:       companyDetail.CityCode,
		AuditStatus:    constants.AuditStatusAudited,
		AuditTime: sql.NullTime{
			Time:  time.Now(),
			Valid: true,
		},
		AuditBy:    request.Operator,
		CreatedBy:  request.Operator,
		CreatedOn:  time.Now(),
		ModifiedBy: request.Operator,
		ModifiedOn: time.Now(),
		IsDeleted:  constants.IsDeletedFalse,
	}
	if request.TenantCode != "" {
		//租户用户提交的品类，审核状态为待审核
		bidCompanyPo.AuditStatus = constants.AuditStatusWaiting
		bidCompanyPo.AuditBy = ""
		bidCompanyPo.AuditTime = sql.NullTime{Valid: false}
		bidCompanyPo.TenantCode = request.TenantCode
	}

	bidCompanyPo, err = s.strategicMonitorRepo.SaveStrategicBidCompany(ctx, bidCompanyPo)
	if err != nil {
		return nil, err
	}

	resp := &pb.AddBidCompanyResponse{Id: bidCompanyPo.Id}
	return resp, nil
}

func (s *strategicMonitorService) GetBidCompanyDetail(ctx context.Context, request *pb.GetBidCompanyDetailRequest) (*pb.GetBidCompanyDetailResponse, error) {
	if request == nil {
		return nil, errors.New("GetBidCompanyDetail参数错误")
	}
	_, bidCompanyList, err := s.strategicMonitorRepo.QueryStrategicBidCompanyList(ctx, map[string]interface{}{"id": request.Id}, nil)
	if err != nil {
		return nil, err
	}

	if len(bidCompanyList) == 0 {
		return nil, errors.New("企业不存在")
	}

	bidCompanyPo := bidCompanyList[0]

	resp := &pb.GetBidCompanyDetailResponse{
		Detail: &pb.BidCompanyItem{
			Id:             bidCompanyPo.Id,
			CompanyName:    bidCompanyPo.CompanyName,
			OrganizingCode: bidCompanyPo.OrganizingCode,
			Province:       bidCompanyPo.Province,
			ProvinceCode:   bidCompanyPo.ProvinceCode,
			City:           bidCompanyPo.City,
			CityCode:       bidCompanyPo.CityCode,
			AuditStatus:    bidCompanyPo.AuditStatus,
			AuditBy:        bidCompanyPo.AuditBy,
			CreatedBy:      bidCompanyPo.CreatedBy,
			CreatedOn:      bidCompanyPo.CreatedBy,
		},
	}
	if bidCompanyPo.AuditTime.Valid {
		resp.Detail.AuditTime = bidCompanyPo.AuditTime.Time.Format("2006-01-02 15:04:05")
	}
	//获取公司的中标数量和合作单位数量
	condition := map[string]interface{}{
		"is_deleted": constants.IsDeletedFalse,
	}
	if bidCompanyPo.OrganizingCode != "" {
		condition["organizing_code"] = bidCompanyPo.OrganizingCode
	} else {
		condition["company_name"] = bidCompanyPo.CompanyName
	}
	bidCount, _, _ := s.strategicMonitorRepo.QueryStrategicBidAuditList(ctx, condition, utils.FirstPageFirstRecord)
	if bidCount != 0 {
		resp.Detail.BidCount = int32(bidCount)
	}

	cooperateCount, _ := s.strategicMonitorRepo.CountBidCompanyCooperate(ctx, bidCompanyPo.CompanyName, bidCompanyPo.OrganizingCode)
	if cooperateCount != 0 {
		resp.Detail.CooperateCount = int32(cooperateCount)
	}

	return resp, nil
}

func buildIndustryListCondition(request *pb.GetIndustryListRequest) map[string]interface{} {
	condition := map[string]interface{}{
		"is_deleted": constants.IsDeletedFalse,
	}
	if request.Keyword != "" {
		condition["keyword"] = request.Keyword
	}
	if len(request.AuditStatus) > 0 {
		condition["audit_status"] = request.AuditStatus
	}
	return condition
}

func (s *strategicMonitorService) GetIndustryList(ctx context.Context, request *pb.GetIndustryListRequest) (*pb.GetIndustryListResponse, error) {
	condition := buildIndustryListCondition(request)
	pageInfo := &utils.PageInfo{PageSize: 20, Page: 1}
	if request.Page > 0 && request.PageSize > 0 {
		pageInfo = &utils.PageInfo{Page: int(request.Page), PageSize: int(request.PageSize)}
	}

	count, industryList, err := s.strategicMonitorRepo.QueryStrategicIndustryList(ctx, condition, pageInfo)
	if err != nil {
		return nil, err
	}
	resp := &pb.GetIndustryListResponse{
		Total: int32(count),
		List:  nil,
	}
	for _, industry := range industryList {
		pbIndustry := &pb.IndustryItem{
			Id:           industry.Id,
			IndustryName: industry.IndustryName,
			AuditStatus:  industry.AuditStatus,
			CreatedBy:    industry.CreatedBy,
			CreatedOn:    industry.CreatedOn.Format("2006-01-02 15:04:05"),
		}

		// 获取品类关联的招中标数量
		bidCount, _ := s.strategicMonitorRepo.CountStrategicBidAuditByIndustryId(ctx, industry.Id)
		if bidCount > 0 {
			pbIndustry.BidCount = int32(bidCount)
		}

		// 获取品类关联的甲方单位数量
		bidCompanyCount, _ := s.strategicMonitorRepo.CountBidCompanyByIndustryId(ctx, industry.Id)
		if bidCompanyCount > 0 {
			pbIndustry.BidCompanyCount = int32(bidCompanyCount)
		}

		// 获取品类关联的合作单位数量
		cooperateCount, _ := s.strategicMonitorRepo.CountBidCompanyCooperateByIndustryId(ctx, industry.Id)
		if cooperateCount > 0 {
			pbIndustry.CooperateCount = int32(cooperateCount)
		}
		resp.List = append(resp.List, pbIndustry)
	}
	return resp, nil
}

func (s *strategicMonitorService) AuditIndustry(ctx context.Context, request *pb.AuditIndustryRequest) (*pb.AuditIndustryResponse, error) {
	if request == nil || request.Id == 0 || request.AuditStatus < constants.AuditStatusWaiting || request.AuditStatus > constants.AuditStatusReject {
		return nil, errors.New("AuditIndustry参数错误")
	}

	condition := map[string]interface{}{"id": request.Id, "is_deleted": constants.IsDeletedFalse}

	count, _, err := s.strategicMonitorRepo.QueryStrategicIndustryList(ctx,
		condition, nil)
	if err != nil {
		return nil, err
	}

	if count == 0 {
		return nil, errors.New("该品类不存在")
	}

	err = s.strategicMonitorRepo.UpdateStrategicIndustry(ctx, condition,
		map[string]interface{}{"audit_status": request.AuditStatus, "audit_by": request.AuditUser, "audit_time": time.Now()})
	if err != nil {
		return nil, err
	}

	return &pb.AuditIndustryResponse{IsSuccess: true}, nil
}

func (s *strategicMonitorService) AddIndustry(ctx context.Context, request *pb.AddIndustryRequest) (*pb.AddIndustryResponse, error) {
	if request == nil || request.IndustryName == "" {
		return nil, errors.New("AddIndustry参数错误")
	}

	// 品类名称不能重复
	count, _, err := s.strategicMonitorRepo.QueryStrategicIndustryList(ctx,
		map[string]interface{}{"industry_name": request.IndustryName, "is_deleted": constants.IsDeletedFalse}, nil)
	if err != nil {
		return nil, err
	}

	if count > 0 {
		return nil, errors.New("该品类已存在")
	}

	industryPo := &strategic_monitor.StrategicIndustry{
		IndustryName: request.IndustryName,
		AuditStatus:  constants.AuditStatusAudited,
		AuditTime: sql.NullTime{
			Time:  time.Now(),
			Valid: true,
		},
		AuditBy:    request.Operator,
		CreatedBy:  request.Operator,
		CreatedOn:  time.Now(),
		ModifiedBy: request.Operator,
		ModifiedOn: time.Now(),
	}

	if request.TenantCode != "" {
		//租户用户提交的品类，审核状态为待审核
		industryPo.AuditStatus = constants.AuditStatusWaiting
		industryPo.AuditBy = ""
		industryPo.AuditTime = sql.NullTime{Valid: false}
		industryPo.TenantCode = request.TenantCode
	}
	industryPo, err = s.strategicMonitorRepo.SaveStrategicIndustry(ctx, industryPo)
	if err != nil {
		return nil, err
	}

	resp := &pb.AddIndustryResponse{
		Id: industryPo.Id,
	}

	return resp, nil
}

func (s *strategicMonitorService) GetCompanyBidList(ctx context.Context, request *pb.GetCompanyBidListRequest) (*pb.GetCompanyBidListResponse, error) {
	if request == nil || request.Id == 0 {
		return nil, errors.New("GetCompanyBidList参数错误")
	}

	_, bidCompanyList, err := s.strategicMonitorRepo.QueryStrategicBidCompanyList(ctx,
		map[string]interface{}{"id": request.Id, "is_deleted": constants.IsDeletedFalse}, utils.FirstPageFirstRecord)
	if err != nil {
		return nil, err
	}
	if len(bidCompanyList) == 0 {
		return nil, errors.New("公司不存在")
	}
	bidCompanyPo := bidCompanyList[0]
	pageInfo := &utils.PageInfo{PageSize: 20, Page: 1}
	if request.Page > 0 && request.PageSize > 0 {
		pageInfo = &utils.PageInfo{Page: int(request.Page), PageSize: int(request.PageSize)}
	}

	count, bidAuditList, err := s.strategicMonitorRepo.QueryStrategicBidAuditList(ctx,
		map[string]interface{}{"organizing_code": bidCompanyPo.OrganizingCode, "is_deleted": constants.IsDeletedFalse}, pageInfo)
	if err != nil {
		return nil, err
	}
	resp := &pb.GetCompanyBidListResponse{
		Total: int32(count),
	}
	for _, bidAudit := range bidAuditList {
		pbCompanyBidAudit := &pb.CompanyBidItem{
			Id:             bidAudit.Id,
			CompanyName:    bidCompanyPo.CompanyName,
			OrganizingCode: bidAudit.OrganizingCode,
			Title:          bidAudit.Title,
			ProcureType:    bidAudit.ProcureType,
			PublishDate:    bidAudit.PublishDate.Format("2006-01-02"),
			StartYear:      bidAudit.StartYear,
			EndYear:        bidAudit.EndYear,
			Industries:     nil,
		}

		industryPoList, _ := s.strategicMonitorRepo.QueryStrategicIndustryByAuditId(ctx, bidAudit.Id)
		for _, industry := range industryPoList {
			pbCompanyBidAudit.Industries = append(pbCompanyBidAudit.Industries, &pb.IndustryItem{
				Id:           industry.Id,
				IndustryName: industry.IndustryName,
				AuditStatus:  industry.AuditStatus,
				CreatedBy:    industry.CreatedBy,
				CreatedOn:    industry.CreatedOn.Format("2006-01-02 15:04:05"),
			})
		}

		resp.List = append(resp.List, pbCompanyBidAudit)
	}

	return resp, nil
}

func (s *strategicMonitorService) GetCompanyCooperateList(ctx context.Context, request *pb.GetCompanyCooperateListRequest) (*pb.GetCompanyCooperateListResponse, error) {
	if request == nil || request.Id == 0 {
		return nil, errors.New("GetCompanyCooperateList参数错误")
	}
	_, bidCompanyList, err := s.strategicMonitorRepo.QueryStrategicBidCompanyList(ctx,
		map[string]interface{}{"id": request.Id, "is_deleted": constants.IsDeletedFalse}, utils.FirstPageFirstRecord)
	if err != nil {
		return nil, err
	}
	if len(bidCompanyList) == 0 {
		return nil, errors.New("公司不存在")
	}
	bidCompanyPo := bidCompanyList[0]
	pageInfo := &utils.PageInfo{PageSize: 20, Page: 1}
	if request.Page > 0 && request.PageSize > 0 {
		pageInfo = &utils.PageInfo{Page: int(request.Page), PageSize: int(request.PageSize)}
	}
	count, cooperateList, err := s.strategicMonitorRepo.GetBidCompanyCooperateByCompanyId(ctx, request.GetId(), pageInfo)
	if err != nil {
		return nil, err
	}
	resp := &pb.GetCompanyCooperateListResponse{
		Total: int32(count),
	}

	var auditIds []int64
	auditIdSet := make(map[int64]bool)
	for _, cooperate := range cooperateList {
		if _, ok := auditIdSet[cooperate.AuditId]; !ok {
			auditIdSet[cooperate.AuditId] = true
			auditIds = append(auditIds, cooperate.AuditId)
		}
	}
	auditBidMap := make(map[int64]*strategic_monitor.StrategicBidAudit)
	if len(auditIds) > 0 {
		_, auditBidList, _ := s.strategicMonitorRepo.QueryStrategicBidAuditList(ctx, map[string]interface{}{"id": auditIds, "is_deleted": constants.IsDeletedFalse}, nil)
		for _, auditBidPo := range auditBidList {
			auditBidMap[auditBidPo.Id] = auditBidPo
		}
	}

	for _, cooperate := range cooperateList {
		pbCompanyCooperate := &pb.CompanyCooperateItem{
			Id:                      cooperate.Id,
			CompanyName:             bidCompanyPo.CompanyName,
			OrganizingCode:          bidCompanyPo.OrganizingCode,
			Industries:              nil,
			CooperateCompanyName:    cooperate.CooperateCompanyName,
			CooperateOrganizingCode: cooperate.CooperateOrganizingCode,
		}
		auditBidInfo, ok := auditBidMap[cooperate.AuditId]
		if ok {
			pbCompanyCooperate.ProcureType = auditBidInfo.ProcureType
			pbCompanyCooperate.PublishDate = auditBidInfo.PublishDate.Format("2006-01-02")
			pbCompanyCooperate.StartYear = auditBidInfo.StartYear
			pbCompanyCooperate.EndYear = auditBidInfo.EndYear
		}

		industryPoList, _ := s.strategicMonitorRepo.QueryStrategicIndustryByAuditId(ctx, cooperate.AuditId)
		for _, industry := range industryPoList {
			pbCompanyCooperate.Industries = append(pbCompanyCooperate.Industries, &pb.IndustryItem{
				Id:           industry.Id,
				IndustryName: industry.IndustryName,
				AuditStatus:  industry.AuditStatus,
				CreatedBy:    industry.CreatedBy,
				CreatedOn:    industry.CreatedOn.Format("2006-01-02 15:04:05"),
			})
		}
		resp.List = append(resp.List, pbCompanyCooperate)
	}

	return resp, nil
}

func readRemoteExcelData(fileDownloadUrl string) ([][]string, [][]string, error) {
	var bidSheetData, cooperateSheetData [][]string
	if fileDownloadUrl == "" {
		return bidSheetData, cooperateSheetData, nil
	}

	resp, err := http.Get(fileDownloadUrl)
	if err != nil {
		return bidSheetData, cooperateSheetData, err
	}

	f, err := excelize.OpenReader(resp.Body)
	if err != nil {
		return bidSheetData, cooperateSheetData, err
	}
	defer func() {
		_ = f.Close()
		_ = resp.Body.Close()
	}()

	bidSheetData, err = f.GetRows("战略集采招标")
	if err != nil {
		return bidSheetData, cooperateSheetData, err
	}
	cooperateSheetData, err = f.GetRows("战略合作单位")
	if err != nil {
		return bidSheetData, cooperateSheetData, err
	}

	return bidSheetData, cooperateSheetData, nil
}

func (s *strategicMonitorService) ImportBidCompany(ctx context.Context, request *pb.ImportBidCompanyRequest) (*pb.ImportBidCompanyResponse, error) {
	if request == nil || request.FileId == "" {
		return nil, errors.New("ImportCompanyBid参数错误")
	}

	//1.获取文件信息,下载文件,读取文件内容
	fileInfo, err := s.fileService.QueryByUid(ctx, request.FileId)
	if err != nil {
		return nil, err
	}
	if fileInfo == nil {
		return nil, errors.New("文件不存在")
	}

	fileUrl, err := ossfile.GetSignURL(fileInfo.FilePath)
	if err != nil {
		return nil, err
	}
	bidSheetData, cooperateSheetData, err := readRemoteExcelData(fileUrl)
	if err != nil {
		return nil, err
	}

	resp := &pb.ImportBidCompanyResponse{}

	succeedList, failedList, err := s.importBid(ctx, bidSheetData, request.Operator)
	if err != nil {
		return nil, err
	}
	resp.SucceedList = append(resp.SucceedList, succeedList...)
	resp.FailedList = append(resp.FailedList, failedList...)

	succeedList, failedList, err = s.importCooperate(ctx, cooperateSheetData, request.Operator)
	if err != nil {
		return nil, err
	}
	resp.SucceedList = append(resp.SucceedList, succeedList...)
	resp.FailedList = append(resp.FailedList, failedList...)

	return resp, nil
}

func (s *strategicMonitorService) DeleteBidAudit(ctx context.Context, request *pb.DeleteBidAuditRequest) (*pb.DeleteBidAuditResponse, error) {
	if request == nil || request.Id == 0 {
		return nil, errors.New("DeleteBidAudit参数错误")
	}

	err := s.strategicMonitorRepo.UpdateStrategicBidAudit(ctx,
		map[string]interface{}{"id": request.Id, "is_deleted": constants.IsDeletedFalse},
		map[string]interface{}{"is_deleted": constants.IsDeletedTrue, "modified_by": request.Operator, "modified_on": time.Now()})
	if err != nil {
		return nil, err
	}
	return &pb.DeleteBidAuditResponse{IsSuccess: true}, nil
}

func (s *strategicMonitorService) DeleteCooperateCompany(ctx context.Context, request *pb.DeleteCooperateCompanyRequest) (*pb.DeleteCooperateCompanyResponse, error) {
	if request == nil || request.Id == 0 {
		return nil, errors.New("DeleteCompanyBid参数错误")
	}

	err := s.strategicMonitorRepo.UpdateStrategicBidCooperateCompany(ctx,
		map[string]interface{}{"id": request.Id, "is_deleted": constants.IsDeletedFalse},
		map[string]interface{}{"is_deleted": constants.IsDeletedTrue, "modified_by": request.Operator, "modified_on": time.Now()})
	if err != nil {
		return nil, err
	}
	return &pb.DeleteCooperateCompanyResponse{IsSuccess: true}, nil
}

func (s *strategicMonitorService) importBid(ctx context.Context, bidSheetData [][]string, operator string) ([]string, []string, error) {
	var succeedList, failedList []string

	//1.文件格式校验
	if len(bidSheetData) <= 2 {
		return nil, nil, errors.New("文件内容为空")
	} else if len(bidSheetData) > 1002 {
		return nil, nil, errors.New("文件内容超过1000行，请分批导入")
	}

	titleRowData := bidSheetData[1]
	if len(titleRowData) != 6 {
		return nil, nil, errors.New("模板内容被修改，导入失败")
	} else {
		if !strings.EqualFold(titleRowData[0], "甲方单位") ||
			!strings.EqualFold(titleRowData[1], "集采标题") ||
			!strings.HasPrefix(titleRowData[2], "集采类型") ||
			!strings.HasPrefix(titleRowData[3], "发布时间") ||
			!strings.HasPrefix(titleRowData[4], "战采周期") ||
			!strings.HasPrefix(titleRowData[5], "战采产品") {
			return nil, nil, errors.New("模板内容被修改，导入失败")
		}
	}

	companyName2OrganizationCodeMap := make(map[string]*openapi_remote.CompanyDetailBo)
	industryName2IndustryPoMap := make(map[string]*strategic_monitor.StrategicIndustry)
	for i := 2; i < len(bidSheetData); i++ {
		if len(bidSheetData[i]) == 0 {
			continue
		}
		if len(bidSheetData[i]) < 6 {
			failedList = append(failedList, fmt.Sprintf("战略集采招标，第%d行【%s】数据不全，导入失败", i+1, strings.Join(bidSheetData[i], "-")))
			continue
		}
		companyName := strings.TrimSpace(bidSheetData[i][0])     //甲方单位名称，需要校验工商信息
		title := strings.TrimSpace(bidSheetData[i][1])           //标题，不超过255个字就好了
		procureTypeName := strings.TrimSpace(bidSheetData[i][2]) //集采类型，需要校验取值枚举：【集团、区域、集团集采、区域集采】
		publishDateStr := strings.TrimSpace(bidSheetData[i][3])  //发布时间，格式校验: 2000-01-01
		yearsStr := strings.TrimSpace(bidSheetData[i][4])        //战采周期，格式校验: 2020-2021
		industryNames := strings.TrimSpace(bidSheetData[i][5])   //合作品类，逗号拼接的字符串

		// 每个值的格式校验
		importData, err := checkInputFormat(companyName, title, procureTypeName, publishDateStr, yearsStr, industryNames, "")
		if err != nil {
			failedList = append(failedList, fmt.Sprintf("战略集采招标，第%d行【%s】%s", i+1, strings.Join(bidSheetData[i], "-"), err.Error()))
			continue
		}

		// 企业社会信用代码检查
		companyDetail, ok := companyName2OrganizationCodeMap[importData.companyName]
		if !ok {
			// 检查公司的工商信息
			companyDetail, err = s.openapiRepo.GetCompanyDetail(ctx, importData.companyName)
			if err != nil {
				failedList = append(failedList, fmt.Sprintf("战略集采招标，第%d行【%s】甲方单位的社会信用代码不存在", i+1, strings.Join(bidSheetData[i], "-")))
				continue
			}
			if companyDetail == nil || companyDetail.OrganizingCode == "" {
				failedList = append(failedList, fmt.Sprintf("战略集采招标，第%d行【%s】甲方单位的社会信用代码不存在", i+1, strings.Join(bidSheetData[i], "-")))
				continue
			}
			importData.organizingCode = companyDetail.OrganizingCode
			companyName2OrganizationCodeMap[importData.companyName] = companyDetail
		} else {
			importData.organizingCode = companyDetail.OrganizingCode
		}

		//检查是否存在一模一样的审核通过的招中标数据
		condition := map[string]interface{}{
			"title":           importData.title,
			"procure_type":    importData.procureType,
			"publish_date":    importData.publishDate,
			"start_year":      importData.startYear,
			"end_year":        importData.endYear,
			"company_name":    importData.companyName,
			"organizing_code": importData.organizingCode,
			"is_deleted":      constants.IsDeletedFalse,
		}

		var auditId int64
		_, list, _ := s.strategicMonitorRepo.QueryStrategicBidAuditList(ctx, condition, nil)
		if len(list) > 0 {
			//已经有相同的招中标数据，更新产品品类即可
			auditId = list[0].Id
		} else {
			//无相同的招中标数据，新增招中标数据
			bidAuditPo, err := s.strategicMonitorRepo.SaveStrategicBidAudit(ctx, &strategic_monitor.StrategicBidAudit{
				Id:             0,
				BidId:          "",
				Title:          importData.title,
				CompanyName:    importData.companyName,
				OrganizingCode: importData.organizingCode,
				PublishDate:    importData.publishDate,
				ProcureType:    int32(importData.procureType),
				StartYear:      int32(importData.startYear),
				EndYear:        int32(importData.endYear),
				CreatedBy:      operator,
				CreatedOn:      time.Now(),
				ModifiedBy:     operator,
				ModifiedOn:     time.Now(),
				IsDeleted:      constants.IsDeletedFalse,
			})
			if err != nil {
				return nil, nil, err
			}
			auditId = bidAuditPo.Id
			//新增甲方单位数据
			count, _, _ := s.strategicMonitorRepo.QueryStrategicBidCompanyList(ctx,
				map[string]interface{}{"organizing_code": importData.organizingCode, "is_deleted": constants.IsDeletedFalse},
				utils.FirstPageFirstRecord)
			if count == 0 {
				//甲方单位不存在
				_, err = s.strategicMonitorRepo.SaveStrategicBidCompany(ctx, &strategic_monitor.StrategicBidCompany{
					Id:             0,
					CompanyName:    importData.companyName,
					OrganizingCode: importData.organizingCode,
					Province:       companyDetail.Province,
					ProvinceCode:   companyDetail.ProvinceCode,
					City:           companyDetail.City,
					CityCode:       companyDetail.CityCode,
					AuditStatus:    constants.AuditStatusAudited,
					AuditTime: sql.NullTime{
						Time:  time.Now(),
						Valid: true,
					},
					AuditBy:    operator,
					CreatedBy:  operator,
					CreatedOn:  time.Now(),
					ModifiedBy: operator,
					ModifiedOn: time.Now(),
					IsDeleted:  constants.IsDeletedFalse,
				})
				if err != nil {
					return nil, nil, err
				}
			}
		}

		//更新产品品类
		var industryIds []int64
		for _, industryName := range importData.industryNames {
			if industryPo, ok := industryName2IndustryPoMap[industryName]; !ok {
				_, industryList, err := s.strategicMonitorRepo.QueryStrategicIndustryList(ctx,
					map[string]interface{}{"industry_name": industryName, "is_deleted": constants.IsDeletedFalse},
					utils.FirstPageFirstRecord)
				if err != nil {
					return nil, nil, err
				}
				if len(industryList) == 0 {
					// 产品品类不存在，直接新增品类
					industryPo, err = s.strategicMonitorRepo.SaveStrategicIndustry(ctx, &strategic_monitor.StrategicIndustry{
						Id:           0,
						IndustryName: industryName,
						AuditStatus:  constants.AuditStatusAudited,
						AuditTime: sql.NullTime{
							Time:  time.Now(),
							Valid: true,
						},
						AuditBy:    operator,
						CreatedBy:  operator,
						CreatedOn:  time.Now(),
						ModifiedBy: operator,
						ModifiedOn: time.Now(),
						IsDeleted:  constants.IsDeletedFalse,
					})
					industryIds = append(industryIds, industryPo.Id)
				} else {
					industryName2IndustryPoMap[industryName] = industryList[0]
					industryIds = append(industryIds, industryList[0].Id)
				}
			} else {
				industryIds = append(industryIds, industryPo.Id)
			}
		}

		if len(industryIds) != 0 {
			// 删除旧的分类，新增新的分类
			err = s.strategicMonitorRepo.UpdateStrategicBidIndustry(ctx, map[string]interface{}{"audit_id": auditId, "is_deleted": constants.IsDeletedFalse},
				map[string]interface{}{"is_deleted": constants.IsDeletedTrue, "modified_by": operator, "modified_on": time.Now()})
			if err != nil {
				return nil, nil, err
			}
		}
		for _, industryId := range industryIds {
			_, err = s.strategicMonitorRepo.SaveStrategicBidIndustry(ctx, &strategic_monitor.StrategicBidIndustry{
				Id:         0,
				AuditId:    auditId,
				IndustryId: industryId,
				CreatedBy:  operator,
				CreatedOn:  time.Now(),
				ModifiedBy: operator,
				ModifiedOn: time.Now(),
				IsDeleted:  constants.IsDeletedFalse,
			})
			if err != nil {
				return nil, nil, err
			}
		}
		succeedList = append(succeedList, fmt.Sprintf("战略集采招标，第%d行【%s】导入成功", i+1, strings.Join(bidSheetData[i], "-")))
	}

	return succeedList, failedList, nil
}

func (s *strategicMonitorService) importCooperate(ctx context.Context, cooperateSheetData [][]string, operator string) ([]string, []string, error) {
	var succeedList, failedList []string

	//1.文件格式校验
	if len(cooperateSheetData) <= 2 {
		return nil, nil, errors.New("文件内容为空")
	} else if len(cooperateSheetData) > 1002 {
		return nil, nil, errors.New("文件内容超过1000行，请分批导入")
	}

	titleRowData := cooperateSheetData[1]
	if len(titleRowData) != 7 {
		return nil, nil, errors.New("模板内容被修改，导入失败")
	} else {
		if !strings.EqualFold(titleRowData[0], "甲方单位") ||
			!strings.EqualFold(titleRowData[1], "集采标题") ||
			!strings.EqualFold(titleRowData[2], "合作单位") ||
			!strings.HasPrefix(titleRowData[3], "集采类型") ||
			!strings.HasPrefix(titleRowData[4], "发布时间") ||
			!strings.HasPrefix(titleRowData[5], "战采周期") ||
			!strings.HasPrefix(titleRowData[6], "战采产品") {
			return nil, nil, errors.New("模板内容被修改，导入失败")
		}
	}

	companyName2OrganizationCodeMap := make(map[string]*openapi_remote.CompanyDetailBo)
	industryName2IndustryPoMap := make(map[string]*strategic_monitor.StrategicIndustry)
	for i := 2; i < len(cooperateSheetData); i++ {
		if len(cooperateSheetData[i]) == 0 {
			continue
		}
		if len(cooperateSheetData[i]) < 7 {
			failedList = append(failedList, fmt.Sprintf("战略合作单位，第%d行【%s】数据不全，导入失败", i+1, strings.Join(cooperateSheetData[i], "-")))
			continue
		}
		companyName := strings.TrimSpace(cooperateSheetData[i][0])          //甲方单位名称，需要校验工商信息
		title := strings.TrimSpace(cooperateSheetData[i][1])                //标题，不超过255个字就好了
		cooperateCompanyName := strings.TrimSpace(cooperateSheetData[i][2]) //合作单位，不超过255个字就好了
		procureTypeName := strings.TrimSpace(cooperateSheetData[i][3])      //集采类型，需要校验取值枚举：【集团、区域、集团集采、区域集采】
		publishDateStr := strings.TrimSpace(cooperateSheetData[i][4])       //发布时间，格式校验: 2000-01-01
		yearsStr := strings.TrimSpace(cooperateSheetData[i][5])             //战采周期，格式校验: 2020-2021
		industryNames := strings.TrimSpace(cooperateSheetData[i][6])        //合作品类，逗号拼接的字符串

		// 每个值的格式校验
		if cooperateCompanyName == "" {
			failedList = append(failedList, fmt.Sprintf("战略合作单位，第%d行【%s】合作单位不能为空", i+1, strings.Join(cooperateSheetData[i], "-")))
			continue
		}
		importData, err := checkInputFormat(companyName, title, procureTypeName, publishDateStr, yearsStr, industryNames, cooperateCompanyName)
		if err != nil {
			failedList = append(failedList, fmt.Sprintf("战略合作单位，第%d行【%s】%s", i+1, strings.Join(cooperateSheetData[i], "-"), err.Error()))
			continue
		}

		// 企业社会信用代码检查
		companyDetail, ok := companyName2OrganizationCodeMap[importData.companyName]
		if !ok {
			// 检查公司的工商信息
			companyDetail, err = s.openapiRepo.GetCompanyDetail(ctx, importData.companyName)
			if err != nil {
				failedList = append(failedList, fmt.Sprintf("战略合作单位，第%d行【%s】甲方单位的社会信用代码不存在", i+1, strings.Join(cooperateSheetData[i], "-")))
				continue
			}
			if companyDetail == nil || companyDetail.OrganizingCode == "" {
				failedList = append(failedList, fmt.Sprintf("战略合作单位，第%d行【%s】甲方单位的社会信用代码不存在", i+1, strings.Join(cooperateSheetData[i], "-")))
				continue
			}
			importData.organizingCode = companyDetail.OrganizingCode
			companyName2OrganizationCodeMap[importData.companyName] = companyDetail
		} else {
			importData.organizingCode = companyDetail.OrganizingCode
		}

		//检查是否存在一模一样的审核通过的招中标数据
		condition := map[string]interface{}{
			"title":           importData.title,
			"procure_type":    importData.procureType,
			"publish_date":    importData.publishDate,
			"start_year":      importData.startYear,
			"end_year":        importData.endYear,
			"company_name":    importData.companyName,
			"organizing_code": importData.organizingCode,
			"is_deleted":      constants.IsDeletedFalse,
		}

		var auditId int64
		_, list, _ := s.strategicMonitorRepo.QueryStrategicBidAuditList(ctx, condition, nil)
		if len(list) > 0 {
			//已经有相同的招中标数据，更新产品品类即可
			auditId = list[0].Id
		} else {
			//无相同的招中标数据，新增招中标数据
			bidAuditPo, err := s.strategicMonitorRepo.SaveStrategicBidAudit(ctx, &strategic_monitor.StrategicBidAudit{
				Id:             0,
				BidId:          "",
				Title:          importData.title,
				CompanyName:    importData.companyName,
				OrganizingCode: importData.organizingCode,
				PublishDate:    importData.publishDate,
				ProcureType:    int32(importData.procureType),
				StartYear:      int32(importData.startYear),
				EndYear:        int32(importData.endYear),
				CreatedBy:      operator,
				CreatedOn:      time.Now(),
				ModifiedBy:     operator,
				ModifiedOn:     time.Now(),
				IsDeleted:      constants.IsDeletedFalse,
			})
			if err != nil {
				return nil, nil, err
			}
			auditId = bidAuditPo.Id
			//新增甲方单位数据
			count, _, _ := s.strategicMonitorRepo.QueryStrategicBidCompanyList(ctx,
				map[string]interface{}{"organizing_code": importData.organizingCode, "is_deleted": constants.IsDeletedFalse},
				utils.FirstPageFirstRecord)
			if count == 0 {
				//甲方单位不存在
				_, err = s.strategicMonitorRepo.SaveStrategicBidCompany(ctx, &strategic_monitor.StrategicBidCompany{
					Id:             0,
					CompanyName:    importData.companyName,
					OrganizingCode: importData.organizingCode,
					Province:       companyDetail.Province,
					ProvinceCode:   companyDetail.ProvinceCode,
					City:           companyDetail.City,
					CityCode:       companyDetail.CityCode,
					AuditStatus:    constants.AuditStatusAudited,
					AuditTime: sql.NullTime{
						Time:  time.Now(),
						Valid: true,
					},
					AuditBy:    operator,
					CreatedBy:  operator,
					CreatedOn:  time.Now(),
					ModifiedBy: operator,
					ModifiedOn: time.Now(),
					IsDeleted:  constants.IsDeletedFalse,
				})
				if err != nil {
					return nil, nil, err
				}
			}
		}

		//更新产品品类
		var industryIds []int64
		for _, industryName := range importData.industryNames {
			if industryPo, ok := industryName2IndustryPoMap[industryName]; !ok {
				_, industryList, err := s.strategicMonitorRepo.QueryStrategicIndustryList(ctx,
					map[string]interface{}{"industry_name": industryName, "is_deleted": constants.IsDeletedFalse},
					utils.FirstPageFirstRecord)
				if err != nil {
					return nil, nil, err
				}
				if len(industryList) == 0 {
					// 产品品类不存在，直接新增品类
					industryPo, err = s.strategicMonitorRepo.SaveStrategicIndustry(ctx, &strategic_monitor.StrategicIndustry{
						Id:           0,
						IndustryName: industryName,
						AuditStatus:  constants.AuditStatusAudited,
						AuditTime: sql.NullTime{
							Time:  time.Now(),
							Valid: true,
						},
						AuditBy:    operator,
						CreatedBy:  operator,
						CreatedOn:  time.Now(),
						ModifiedBy: operator,
						ModifiedOn: time.Now(),
						IsDeleted:  constants.IsDeletedFalse,
					})
					industryIds = append(industryIds, industryPo.Id)
				} else {
					industryName2IndustryPoMap[industryName] = industryList[0]
					industryIds = append(industryIds, industryList[0].Id)
				}
			} else {
				industryIds = append(industryIds, industryPo.Id)
			}
		}

		if len(industryIds) != 0 {
			// 删除旧的分类，新增新的分类
			err = s.strategicMonitorRepo.UpdateStrategicBidIndustry(ctx, map[string]interface{}{"audit_id": auditId, "is_deleted": constants.IsDeletedFalse},
				map[string]interface{}{"is_deleted": constants.IsDeletedTrue, "modified_by": operator, "modified_on": time.Now()})
			if err != nil {
				return nil, nil, err
			}
		}
		for _, industryId := range industryIds {
			_, err = s.strategicMonitorRepo.SaveStrategicBidIndustry(ctx, &strategic_monitor.StrategicBidIndustry{
				Id:         0,
				AuditId:    auditId,
				IndustryId: industryId,
				CreatedBy:  operator,
				CreatedOn:  time.Now(),
				ModifiedBy: operator,
				ModifiedOn: time.Now(),
				IsDeleted:  constants.IsDeletedFalse,
			})
			if err != nil {
				return nil, nil, err
			}
		}
		succeedList = append(succeedList, fmt.Sprintf("战略合作单位，第%d行【%s】导入成功", i+1, strings.Join(cooperateSheetData[i], "-")))

		//更新合作单位数据
		count, _, err := s.strategicMonitorRepo.QueryStrategicBidCooperateCompanyList(ctx,
			map[string]interface{}{
				"audit_id":               auditId,
				"cooperate_company_name": importData.cooperateCompanyName,
				"is_deleted":             constants.IsDeletedFalse,
			},
			utils.FirstPageFirstRecord)
		if err != nil {
			return nil, nil, err
		}
		if count == 0 {
			_, err = s.strategicMonitorRepo.SaveStrategicBidCooperateCompany(ctx, &strategic_monitor.StrategicBidCooperateCompany{
				Id:                      0,
				AuditId:                 auditId,
				CooperateCompanyName:    importData.cooperateCompanyName,
				CooperateOrganizingCode: "",
				CreatedBy:               operator,
				CreatedOn:               time.Now(),
				ModifiedBy:              operator,
				ModifiedOn:              time.Now(),
				IsDeleted:               constants.IsDeletedFalse,
			})
			if err != nil {
				return nil, nil, err
			}
		}
	}

	return succeedList, failedList, nil
}

type importBidRowData struct {
	companyName          string
	organizingCode       string
	title                string
	procureType          int
	publishDate          time.Time
	startYear            int
	endYear              int
	industryNames        []string
	cooperateCompanyName string
}

func checkInputFormat(companyName, title, procureTypeName, publishDateStr, yearsStr, industryNamesStr, cooperateCompanyName string) (*importBidRowData, error) {
	if companyName == "" {
		return nil, fmt.Errorf("甲方单位不能为空")
	}
	if title == "" {
		return nil, fmt.Errorf("标题不能为空")
	}
	if procureTypeName == "" {
		return nil, fmt.Errorf("集采类型不能为空")
	}
	if publishDateStr == "" {
		return nil, fmt.Errorf("发布时间不能为空")
	}
	if yearsStr == "" {
		return nil, fmt.Errorf("战采周期不能为空")
	}
	if industryNamesStr == "" {
		return nil, fmt.Errorf("合作品类不能为空")
	}

	data := &importBidRowData{
		companyName:          companyName,
		title:                title,
		cooperateCompanyName: cooperateCompanyName,
	}

	if strings.HasPrefix(procureTypeName, "集团") {
		data.procureType = 1
	} else if strings.HasPrefix(procureTypeName, "区域") {
		data.procureType = 2
	} else {
		return nil, fmt.Errorf("集采类型错误")
	}

	var err error
	publishDateStr = strings.ReplaceAll(publishDateStr, "/", "-")
	data.publishDate, err = time.ParseInLocation("2006-01-02", publishDateStr, time.Local)
	if err != nil {
		return nil, fmt.Errorf("发布时间格式错误")
	}

	yearArr := strings.Split(yearsStr, "-")
	if len(yearArr) != 2 {
		return nil, fmt.Errorf("战采周期格式错误")
	} else {
		data.startYear, err = strconv.Atoi(yearArr[0])
		if err != nil {
			return nil, fmt.Errorf("战采周期格式错误")
		}
		data.endYear, err = strconv.Atoi(yearArr[1])
		if err != nil {
			return nil, fmt.Errorf("战采周期格式错误")
		}
	}

	data.industryNames = strings.Split(strings.ReplaceAll(industryNamesStr, "，", ","), ",")
	if len(data.industryNames) == 0 {
		return nil, fmt.Errorf("战采产品不能为空")
	}

	return data, nil
}

func (s *strategicMonitorService) GetIndustryByNames(ctx context.Context, request *pb.GetIndustryByNamesRequest) (*pb.GetIndustryByNamesResponse, error) {
	if request == nil || len(request.IndustryNameArr) == 0 {
		return nil, errors.New("GetIndustryByNames参数为空")
	}

	_, industryList, err := s.strategicMonitorRepo.QueryStrategicIndustryList(ctx,
		map[string]interface{}{"industry_name": request.IndustryNameArr, "is_deleted": constants.IsDeletedFalse},
		&utils.PageInfo{Page: 1, PageSize: len(request.IndustryNameArr)})
	if err != nil {
		return nil, err
	}
	resp := &pb.GetIndustryByNamesResponse{}
	for _, industry := range industryList {
		pbIndustry := &pb.IndustryItem{
			Id:           industry.Id,
			IndustryName: industry.IndustryName,
			AuditStatus:  industry.AuditStatus,
			CreatedBy:    industry.CreatedBy,
			CreatedOn:    industry.CreatedOn.Format("2006-01-02 15:04:05"),
		}

		// 获取品类关联的招中标数量
		bidCount, _ := s.strategicMonitorRepo.CountStrategicBidAuditByIndustryId(ctx, industry.Id)
		if bidCount > 0 {
			pbIndustry.BidCount = int32(bidCount)
		}

		// 获取品类关联的甲方单位数量
		bidCompanyCount, _ := s.strategicMonitorRepo.CountBidCompanyByIndustryId(ctx, industry.Id)
		if bidCompanyCount > 0 {
			pbIndustry.BidCompanyCount = int32(bidCompanyCount)
		}

		// 获取品类关联的合作单位数量
		cooperateCount, _ := s.strategicMonitorRepo.CountBidCompanyCooperateByIndustryId(ctx, industry.Id)
		if cooperateCount > 0 {
			pbIndustry.CooperateCount = int32(cooperateCount)
		}
		resp.List = append(resp.List, pbIndustry)
	}

	return resp, nil
}

func (s *strategicMonitorService) GetBidCompanyByCodes(ctx context.Context, request *pb.GetBidCompanyByCodesRequest) (*pb.GetBidCompanyByCodesResponse, error) {
	if request == nil || len(request.OrganizingCodeArr) == 0 {
		return nil, errors.New("GetBidCompanyByNames参数错误")
	}
	_, bidCompanyList, err := s.strategicMonitorRepo.QueryStrategicBidCompanyList(ctx,
		map[string]interface{}{"organizing_code": request.OrganizingCodeArr, "is_deleted": constants.IsDeletedFalse},
		&utils.PageInfo{Page: 1, PageSize: len(request.OrganizingCodeArr)})
	if err != nil {
		return nil, err
	}
	resp := &pb.GetBidCompanyByCodesResponse{}
	if len(bidCompanyList) == 0 {
		return resp, nil
	}
	for _, bidCompanyPo := range bidCompanyList {
		bidCompanyPbItem := &pb.BidCompanyItem{
			Id:             bidCompanyPo.Id,
			CompanyName:    bidCompanyPo.CompanyName,
			OrganizingCode: bidCompanyPo.OrganizingCode,
			Province:       bidCompanyPo.Province,
			ProvinceCode:   bidCompanyPo.ProvinceCode,
			City:           bidCompanyPo.City,
			CityCode:       bidCompanyPo.CityCode,
			AuditStatus:    bidCompanyPo.AuditStatus,
			AuditBy:        bidCompanyPo.AuditBy,
			CreatedBy:      bidCompanyPo.CreatedBy,
			CreatedOn:      bidCompanyPo.CreatedOn.Format("2006-01-02 15:04:05"),
		}

		if bidCompanyPo.AuditTime.Valid {
			bidCompanyPbItem.AuditTime = bidCompanyPo.AuditTime.Time.Format("2006-01-02 15:04:05")
		}
		//获取公司的中标数量和合作单位数量
		condition := map[string]interface{}{
			"is_deleted": constants.IsDeletedFalse,
		}
		if bidCompanyPo.OrganizingCode != "" {
			condition["organizing_code"] = bidCompanyPo.OrganizingCode
		} else {
			condition["company_name"] = bidCompanyPo.CompanyName
		}
		bidCount, _, _ := s.strategicMonitorRepo.QueryStrategicBidAuditList(ctx, condition, utils.FirstPageFirstRecord)
		if bidCount != 0 {
			bidCompanyPbItem.BidCount = int32(bidCount)
		}

		cooperateCount, _ := s.strategicMonitorRepo.CountBidCompanyCooperate(ctx, bidCompanyPo.CompanyName, bidCompanyPo.OrganizingCode)
		if cooperateCount != 0 {
			bidCompanyPbItem.CooperateCount = int32(cooperateCount)
		}
		resp.List = append(resp.List, bidCompanyPbItem)
	}

	return resp, nil
}

// GetMonitorResult 根据租户监控的品类和公司，获取最终的监控结果数据
func (s *strategicMonitorService) GetMonitorResult(ctx context.Context, request *pb.GetMonitorResultRequest) (*pb.GetMonitorResultResponse, error) {
	if request == nil {
		return nil, errors.New("GetMonitorResult参数错误")
	} else if len(request.IndustryNameList) == 0 && len(request.OrganizingCodeList) == 0 {
		return nil, errors.New("产品品类和客户都为空")
	}
	// 默认取10个客户
	if request.Page <= 0 {
		request.Page = 1
	}
	if request.PageSize <= 0 {
		request.PageSize = 10
	}

	// 监控品类不为空，根据品类查询甲方单位
	if len(request.IndustryNameList) != 0 {
		organizingCodeList, err := s.strategicMonitorRepo.QueryBidCompanyOrganizingCodeByIndustryName(ctx, request.IndustryNameList)
		if err != nil {
			return nil, err
		}
		fmt.Println(organizingCodeList)
		request.OrganizingCodeList = append(request.OrganizingCodeList, organizingCodeList...)
	}

	total, list, err := s.strategicMonitorRepo.QueryStrategicBidCompanyList(ctx,
		map[string]interface{}{"organizing_code": request.OrganizingCodeList, "is_deleted": constants.IsDeletedFalse},
		&utils.PageInfo{Page: int(request.Page), PageSize: int(request.PageSize)})
	if err != nil {
		return nil, err
	}
	resp := &pb.GetMonitorResultResponse{
		Total: int32(total),
	}

	if len(list) == 0 {
		return resp, nil
	}
	// 取最新发布且审核通过的2条招中标
	// 取最近的4个合作单位
	for _, company := range list {
		pbResultItem := &pb.MonitorResultItem{
			CompanyName:      company.CompanyName,
			OrganizingCode:   company.OrganizingCode,
			StrategicDynamic: nil,
			CooperateCompany: nil,
		}
		_, auditList, err := s.strategicMonitorRepo.QueryStrategicBidAuditList(ctx,
			map[string]interface{}{"organizing_code": company.OrganizingCode}, &utils.PageInfo{Page: 1, PageSize: 2})
		if err != nil {
			return nil, err
		}
		for _, bidAudit := range auditList {
			pbResultItem.StrategicDynamic = append(pbResultItem.StrategicDynamic, &pb.StrategicDynamic{
				Id:                bidAudit.Id,
				ProcureType:       bidAudit.ProcureType,
				PublishDate:       bidAudit.PublishDate.Format("2006-01-02 15:04:05"),
				Title:             bidAudit.Title,
				DeduceNextBidDate: fmt.Sprintf("%d-%s-01 00:00:00", bidAudit.EndYear, bidAudit.PublishDate.Format("01")),
			})
		}

		// 优先取品类关联的合作单位
		cooperateBoList, err := s.strategicMonitorRepo.GetCooperateNameByBidCompanyAndIndustry(ctx, company.OrganizingCode, request.IndustryNameList, &utils.PageInfo{Page: 1, PageSize: 4})
		if err != nil {
			return nil, err
		}
		for _, bo := range cooperateBoList {
			pbResultItem.CooperateCompany = append(pbResultItem.CooperateCompany, &pb.CooperateCompany{
				CooperateCompanyName: bo.CooperateCompanyName,
				PublishDate:          strings.Split(bo.PublishDates, ",")[0],
				IndustryNames:        strings.Split(bo.IndustryNames, ","),
			})
		}

		resp.List = append(resp.List, pbResultItem)
	}

	return resp, nil
}
